package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constant.WmNewsMessageConstants;
import com.heima.model.admin.dtos.ChannelDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmChannelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    /**
     * 修改频道
     *
     * @param wmChannel
     * @return
     */
    @Override
    public ResponseResult updateChannel(WmChannel wmChannel) {
        //检查参数
        if(wmChannel == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.判断频道名称是否发生变化
        WmChannel preWmChannel = getById(wmChannel.getId());
        if(!Objects.equals(preWmChannel.getName(), wmChannel.getName())){
            //频道名称不能重复
            List<WmChannel> list = list();
            List<String> wmChannelNameList = list.stream().map(WmChannel::getName).collect(Collectors.toList());
            if(wmChannelNameList.contains(wmChannel.getName())){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"频道名称不能重复");
            }
            //修改文章中的channelName
            ListenableFuture<SendResult<String, String>> send = kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UPDATE_CHANNEL_TOPIC, JSON.toJSONString(wmChannel));
            send.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
                @Override
                public void onFailure(Throwable throwable) {
                    log.error("【发送修改频道消息失败】");
                    throw  new RuntimeException(throwable);
                }

                @Override
                public void onSuccess(SendResult<String, String> stringStringSendResult) {
                    log.info("【修改频道消息发送成功】");
                }
            });
        }
        //频道被引用则不能禁用
        if(!wmChannel.getStatus()){
            List<WmNews> wmNewsList = wmNewsMapper.selectList(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getChannelId, wmChannel.getId()));
            if(wmNewsList != null && wmNewsList.size() > 0){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"频道被引用则不能禁用");
            }
        }
        updateById(wmChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除频道
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteChannel(Integer id) {
        log.info("【删除频道】--- begin");
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmChannel wmChannel = getById(id);
        if(wmChannel == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if(wmChannel.getStatus()){
            return ResponseResult.errorResult(AppHttpCodeEnum.CHANNEL_ON_USED);
        }
        removeById(id);
        log.info("【删除频道】--- end");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存频道
     *
     * @param wmChannel
     * @return
     */
    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {
        log.info("【保存频道】--- begin");
        if (wmChannel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(wmChannel.getStatus() == null){
            wmChannel.setStatus(false);
        }
        wmChannel.setIsDefault(true);
        wmChannel.setCreatedTime(new Date());

        //频道名称不能重复
        List<WmChannel> list = list();
        List<String> wmChannelNameList = list.stream().map(WmChannel::getName).collect(Collectors.toList());
        if(wmChannelNameList.contains(wmChannel.getName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"频道名称不能重复");
        }

        save(wmChannel);

        log.info("【保存频道】--- end");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询所有频道
     *
     * @return
     */
    @Override
    public ResponseResult findAllChannel() {
        LambdaQueryWrapper<WmChannel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //启用状态筛选
        lambdaQueryWrapper.eq(WmChannel::getStatus,1);
        return ResponseResult.okResult(list(lambdaQueryWrapper));
    }

    /**
     * 模糊分页查询频道
     * @param channelDto
     */
    @Override
    public ResponseResult list(ChannelDto channelDto) {
        log.info("【模糊分页查询频道】--- begin");
        log.info("【参数】--- {}",channelDto);
        //1.检查参数
        if(channelDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页查询
        IPage page = new Page(channelDto.getPage(),channelDto.getSize());
        LambdaQueryWrapper<WmChannel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //名称模糊查询
        lambdaQueryWrapper.like(WmChannel::getName,channelDto.getName());
        //按照时间倒叙
        lambdaQueryWrapper.orderByDesc(WmChannel::getCreatedTime);
        //按照状态精准查询
        //pass

        page = page(page, lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(channelDto.getPage(), channelDto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        log.info("【查询结果】---{}",responseResult);
        log.info("【模糊分页查询频道】--- end");
        return responseResult;
    }
}
